package com.hzit.servlet;

import cn.hutool.core.util.StrUtil;
import com.hzit.entity.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@WebServlet("/student")
public class StudentServlet extends HttpServlet {

	private List<Student> students;

	//1. 初始化学生列表
	@Override
	public void init() throws ServletException {
		students = new ArrayList<>();
		//1.1 构造学生对象
		Student st1 = new Student(1001,"张三","男",20,"上海",1);
		Student st2 = new Student(1002,"李四","男",21,"武汉",3);
		Student st3 = new Student(1003,"王五","女",19,"深圳",2);
		//1.2 添加学生到集合中
		students.add(st1);
		students.add(st2);
		students.add(st3);
	}

	//2. 根据用户请求参数cmd调用不同的方法
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//2.1 得到用户请求参数
		String cmd = req.getParameter("cmd");
		//2.2 根据参数内容确定跳转到指定方法
		if(StrUtil.isNotBlank(cmd)){
			if("list".equals(cmd)){     // 列表学生
				list(req,resp);
			}
		}
	}
	//3. 列表学生
	private void list(HttpServletRequest req, HttpServletResponse resp)  throws ServletException, IOException {
		//1. 将学生列表放到请求作用域中
		req.setAttribute("students",students);
		//2. 进行页面的跳转
		req.getRequestDispatcher("/WEB-INF/students/list.jsp").forward(req,resp);
	}
}

